import { Component, createRef } from 'react'
import { Link } from 'react-router-dom'
import ReactQuill from 'react-quill'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Select,
  Upload,
  Space,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'

import { http } from '../../utils/http'
import { history } from '../../utils/history'

import 'react-quill/dist/quill.snow.css'
import './index.scss'

const { Option } = Select

class Publish extends Component {
  state = {
    channels: [],
    maxCount: 1,
    fileList: []
  }

  formRef = createRef()
  isEdit = this.props.match.params.articleId !== undefined

  async componentDidMount() {
    const res = await http.get('/channels')
    const { channels } = res.data.data

    this.setState({
      channels
    })

    const { articleId } = this.props.match.params
    if (articleId) {
      // 编辑
      // 获取文章信息
      const res = await http.get(`/mp/articles/${articleId}`)

      const {
        id,
        title,
        channel_id,
        content,
        cover: { type, images }
      } = res.data.data
      this.formRef.current.setFieldsValue({
        title,
        channel_id,
        content,
        type,
        id
      })
      this.setState({
        fileList: images.map(item => ({ url: item }))
      })
    }
  }

  changeType = e => {
    this.setState({
      maxCount: e.target.value
    })
  }

  handleChange = data => {
    this.setState({
      fileList: data.fileList
    })
  }

  saveArticles = async (values, saveType) => {
    const { type, ...rest } = values

    const { fileList } = this.state
    const images = fileList.map(item => {
      return item.response.data.url
    })

    const data = {
      ...rest,
      cover: {
        type,
        images
      }
    }

    try {
      // true 草稿
      // false 正常发布
      await http.post(
        `/mp/articles?draft=${saveType === 'add' ? false : true}`,
        data
      )

      const showMsg = this.isEdit ? '修改成功' : '发布成功'
      message.success(showMsg, 1, () => {
        history.push('/home/article')
      })
    } catch {}
  }

  onFinish = async values => {
    this.saveArticles(values, 'add')
  }

  saveDraft = async () => {
    try {
      const values = await this.formRef.current.validateFields()

      // console.log(values)
      this.saveArticles(values, 'draft')
    } catch {}
  }

  render() {
    return (
      <div>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {this.isEdit ? '修改文章' : '发布文章'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={this.formRef}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ type: 1, content: '' }}
            onFinish={this.onFinish}
          >
            <Form.Item hidden name="id">
              <Input type="hidden" />
            </Form.Item>
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '请输入文章标题' }]}
            >
              <Input placeholder="请输入文章标题" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择文章频道' }]}
            >
              <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                {this.state.channels.map(item => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="封面">
              <Form.Item name="type">
                <Radio.Group onChange={this.changeType}>
                  <Radio value={1}>单图</Radio>
                  <Radio value={3}>三图</Radio>
                  <Radio value={0}>无图</Radio>
                  <Radio value={-1}>自动</Radio>
                </Radio.Group>
              </Form.Item>
              {this.state.maxCount > 0 && (
                <Upload
                  name="image"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList
                  action="http://geek.itheima.net/v1_0/upload"
                  fileList={this.state.fileList}
                  onChange={this.handleChange}
                  maxCount={this.state.maxCount}
                  multiple={this.state.maxCount > 1}
                >
                  <div style={{ marginTop: 8 }}>
                    <PlusOutlined />
                  </div>
                </Upload>
              )}
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入文章内容' }]}
            >
              <ReactQuill
                className="publish-quill"
                theme="snow"
                placeholder="请输入文章内容"
              />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  {this.isEdit ? '修改文章' : '发布文章'}
                </Button>
                <Button size="large" onClick={this.saveDraft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
}

export default Publish
